package org.breathe.datastruct.impl;

import lombok.Setter;
import org.breathe.datastruct.RedisBytes;
import org.breathe.datastruct.RedisData;
import org.breathe.internal.Sds;
import org.breathe.protocal.Resp;
import org.breathe.protocal.decode.BulkString;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: breathe
 * @createTime: 2025-05-12
 */
public class RedisString implements RedisData {
    //FIXME 这里的volatile不是为了维护可见性, 是由很多的其他线程，执行命令就一个线程
    private volatile long timeout = -1;
    @Setter
    private Sds value;
    public RedisString(Sds value) {
        this.value = value;
    }
    @Override
    public long timeout() {
        return timeout;
    }

    @Override
    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }

    @Override
    public List<Resp> convertToResp() {
        if (value == null) {
            return Collections.emptyList();
        }
        return Collections.singletonList(new BulkString(getValue()));
    }

    public RedisBytes getValue() {
        return new RedisBytes(value.getBytes());
    }
    public long incr() {
        try {
            long cur = Long.parseLong(value.toString());
            long newValue = cur + 1;
            value = new Sds(String.valueOf(newValue).getBytes());
            return newValue;
        } catch (Exception ex) {
            throw new IllegalArgumentException("value is not a number");
        }
    }
}
